package com.aloda.service.impl;

import com.aloda.constant.ErrorCode;
import com.aloda.constant.ExceptionConstant;
import com.aloda.context.UserBaseContext;
import com.aloda.entity.UserFollow;
import com.aloda.exception.WarnException;
import com.aloda.mapper.FollowMapper;
import com.aloda.mapper.UserMapper;
import com.aloda.service.FollowService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, UserFollow> implements FollowService {

    @Resource
    private FollowMapper followMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 关注
     *
     * @param id 关注用户的id
     * @return 是否成功
     */
    @Override
    @Transactional
    public Boolean followeeUser(Long id) {
        // 1.校验id
        if (id == null) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        // 2.查询是否关注 后期考虑幂等性
        Long userId = UserBaseContext.getUser().getId();
        if (userId.equals(id)) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        Integer count = followMapper.selectIsFollowee(id, userId);
        if (count > 0 ) {
            throw new WarnException(ExceptionConstant.IS_FOLLOW);
        }
        // 3.新增关注
        UserFollow userFollow = new UserFollow();
        userFollow.setFollowUserId(id);
        userFollow.setUserId(userId);
        userFollow.setCreateTime(LocalDateTime.now());
        userMapper.updateUserFollowsIncrease(userId);
        userMapper.updateUserFansIncrease(id);
        int insert = followMapper.insert(userFollow);
        return insert > 0;
    }

    /**
     * 取消关注用户
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Boolean cancelFollowUser(Long id) {
        // 1.校验id
        if (id == null) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        // 2.取消关注
        Long userId = UserBaseContext.getUser().getId();
        LambdaQueryWrapper<UserFollow> userFollowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userFollowLambdaQueryWrapper.eq(UserFollow::getUserId, userId)
                .eq(UserFollow::getFollowUserId, id);
        userMapper.updateUserFollowsDecrease(userId);
        userMapper.updateUserFansDecrease(id);
        int delete = followMapper.delete(userFollowLambdaQueryWrapper);
        return delete > 0;
    }
}
